class MaintenanceController < ApplicationController
  before_filter :sys_before_log
  
  #获取maintenance列表，带分页
  def getMaintenances
    total_property = Maintenance.countByTrainTaskId(params[:trainTaskId])
    maintenances = Maintenance.findPageByTrainTaskId(params[:start].to_i,
      params[:limit].to_i,params[:trainTaskId])
    maintenances.each do |mt|
      mt.description = getWorker mt.checkrecords
    end
    jsonstr='{total:' + total_property.to_s + ',root:' + 
      maintenances.to_json(:include => [:work,:team,:worker]) + '}'                     #组合json串
    render :text=>jsonstr, :layout=>false
  end

  def create
    if DateTime.parse(params[:begin_time]) -
        DateTime.parse(params[:finish_time]) > 0                                #如果开始时间比结束时间晚，就返回错误
      info = '结束时间不能早于开始时间，请修改'
    else
      begin
        maintenance = Maintenance.new
        maintenance.train_task_id = params[:trainTaskId]
        maintenance.team_id = params[:team_id]
        maintenance.work_id = params[:work_id]
        maintenance.begin_time = params[:begin_time]
        maintenance.finish_time = params[:finish_time]
        maintenance.description = params[:description]
        maintenance.save!
        info = 'success'
      rescue Exception => e
        logger.info e
        info = '创建异常'
      end
    end

    result = "{success:true,info:\"#{info}\"}"
    render :text => result,:layout => false
  end

  def assign
    begin
      maintenance = Maintenance.find_by_id(params[:id])
      maintenance.dynamic_flag = params[:type]
      maintenance.save!
      info = 'success'
    rescue Exception=>e
      logger.info e
      info = '操作异常'
    end
    result = "{success:true,info:\"#{info}\"}"
    render :text=>result, :layout=>false
  end

  def delete
    begin
      ids= params[:id][1..params[:id].length-2].split(',')
      Maintenance.destroy(ids)
      info = 'success'
    rescue Exception=>e
      logger.info e
      info = '删除异常'
    end
    result = "{success:true,info:\"#{info}\"}"
    render :text=>result, :layout=>false
  end
  
  def edit
    maintenance = Maintenance.find(params[:id])
    json_str = maintenance.to_json()
    render :text=>json_str,:layout=>false
  end

  def update
    begin
      maintenance = Maintenance.find(params[:id])
      maintenance.team_id = params[:team_id]
      maintenance.work_id = params[:work_id]
      maintenance.begin_time = params[:begin_time]
      maintenance.finish_time = params[:finish_time]
      maintenance.description = params[:description]
      maintenance.save
      info = 'success'
    rescue Exception=>e
      logger.info e
      info = '更新异常'
    end
    result = "{success:true,info:\"#{info}\"}"
    render :text=>result, :layout=>false
  end

  #准备chart图需要的数据（时间段拉伸图）
  #共需要： begin_minute + un_strat_minute
  def getCharts                                                                 #获取chart的数据
    nowTime = Time.now.to_json                                                  #当前时间
    maintenances = Maintenance.findByTrainTaskId(params[:trainTaskId])          #得到维护单元数组
    trainTask = TrainTask.find(params[:trainTaskId])
    taskBeginTime = trainTask.begin_time.to_s                                   #总任务开始时间

    newTeam = Team.find_last_by_name('调度室')
    newWork = Work.find_last_by_name('断电')
    shutDownMaintenance = Maintenance.new                                     #建立断电进度条
    shutDownMaintenance.begin_time = trainTask.begin_time - 1                 #比总计划开始时间早一秒，即能保证此项目排在最前面
    shutDownMaintenance.work = newWork
    shutDownMaintenance.team = newTeam
    shutDownMaintenance.begin_minute = 0
    shutDownMaintenance.title = "接触网供断电"
    #产生动态的断电进度：
    if trainTask.is_end == 0
      shutDownMaintenance.check_in_time = trainTask.begin_time - 1
      shutDownMaintenance.during_minute =
        (DateTime.parse(nowTime) - DateTime.parse(taskBeginTime))*24*60  #现在时间减去任务开始时间 
      shutDownMaintenance.description = '等待断电'
      extraTime = DateTime.parse(nowTime) - DateTime.parse(taskBeginTime)
    else                     
      checkOutTime = trainTask.check_out_time.to_s
      shutDownMaintenance.check_in_time = trainTask.begin_time - 1
      shutDownMaintenance.check_out_time = trainTask.check_out_time.to_s
      shutDownMaintenance.finish_minute =
        (DateTime.parse(checkOutTime) - DateTime.parse(taskBeginTime))*24*60  #现在时间减去任务开始时间
      shutDownMaintenance.description = '断电时间：'+trainTask.check_out_time.strftime('%Y-%m-%d %H:%M')
      extraTime = DateTime.parse(checkOutTime) - DateTime.parse(taskBeginTime)

      if trainTask.power_time
        shutDownMaintenance.description += ' 供电时间：'+trainTask.power_time.strftime('%Y-%m-%d %H:%M')
        shutDownMaintenance.end_minute = (DateTime.parse(trainTask.power_time.to_s)-DateTime.parse(checkOutTime))*24*60
        if trainTask.end_time
          shutDownMaintenance.dynamic_end_minute = (DateTime.parse(trainTask.end_time.to_s)-DateTime.parse(trainTask.power_time.to_s))*24*60
        else
          shutDownMaintenance.dynamic_end_minute = (DateTime.parse(nowTime)-DateTime.parse(trainTask.power_time.to_s))*24*60
        end
      else
        shutDownMaintenance.end_minute = (DateTime.parse(nowTime)-DateTime.parse(checkOutTime))*24*60
      end
    end

    maintenancesTimer = -1
    for maintenance in maintenances                                             #循环维护单元
      beginTime = maintenance.begin_time.to_s                                   #规定开始时间
      finishTime = maintenance.finish_time.to_s                                 #规定结束时间
      checkInTime = maintenance.check_in_time.to_s                              #打卡开始时间
      checkOutTime = maintenance.check_out_time.to_s                            #打卡结束时间
      dynamicCheckInTime = maintenance.dynamic_check_in_time.to_s               #动态打卡开始
      dynamicCheckOutTime = maintenance.dynamic_check_out_time.to_s             #动态结束时间
      dynamicFlag = maintenance.dynamic_flag                                    #是否进行动态作业

      if maintenance.flag.to_i >= 1                                             #新生成的maintenance的flag是小于0的，大于0的都是计划进度
        maintenance.begin_minute =
          (DateTime.parse(beginTime) - DateTime.parse(taskBeginTime)+extraTime)*24*60     #开始时间减去项目总开始时间
        maintenance.un_start_minute =
          (DateTime.parse(finishTime) - DateTime.parse(beginTime))*24*60        #工作结束时间减去工作开始时间
        maintenance.title = maintenance.team.name.to_s + '的'+
          maintenance.work.name.to_s + "任务:计划"
        
        if maintenance.dynamic_flag == 1
          if trainTask.power_time
            a = (DateTime.parse(trainTask.power_time.to_s) - DateTime.parse(finishTime) - extraTime)*24*60
            if a > 2
              maintenance.foot_minute = a
            else
              maintenance.un_start_minute = (DateTime.parse(trainTask.power_time.to_s) - DateTime.parse(beginTime) - extraTime)*24*60 - 2
              maintenance.foot_minute = 2
            end
            maintenance.dynamic_un_start_minute = (maintenance.dynamic_un_start_minute || 40)
          else
            maintenance.dynamic_un_start_minute = 0
          end
        end
          
        if trainTask.is_end != 0
          
          #根据维护单元的类型：计划、打卡进行、打卡完成。
          #原有的计划还要显示，后两种会产生新的进度条。

          #断电，开始静态作业，如果有checkInTime，则新加进行中进度条
          if maintenance.flag.to_s == '2'                                         #如果打卡进行,新建一条记录，用于展示“正在进行时间”，且原有计划继续保留
            if checkInTime != ''
              maintenanceGoingOn = Maintenance.new                                  #新建进度条
              maintenanceGoingOn.begin_minute =
                (DateTime.parse(checkInTime) - DateTime.parse(taskBeginTime))*24*60 #打卡开始时间减去总任务开始时间
              #              maintenanceGoingOn.during_minute =
              #                (DateTime.parse(nowTime) - DateTime.parse(checkInTime))*24*60         #现在时间减去打卡开始时间
              if trainTask.power_time
                if trainTask.power_time > maintenance.check_in_time
                  maintenanceGoingOn.during_minute =
                    (DateTime.parse(trainTask.power_time.to_s) - DateTime.parse(checkInTime))*24*60
                  maintenanceGoingOn.dynamic_during_minute =
                    (DateTime.parse(nowTime) - DateTime.parse(trainTask.power_time.to_s))*24*60
                else
                  maintenanceGoingOn.dynamic_during_minute =
                    (DateTime.parse(nowTime) - DateTime.parse(checkInTime))*24*60
                end
                
              else
                maintenanceGoingOn.during_minute =
                  (DateTime.parse(nowTime) - DateTime.parse(checkInTime))*24*60
              end
              maintenanceGoingOn.train_task_id = maintenance.train_task_id
              maintenanceGoingOn.id = maintenancesTimer                               #设置id，使用递减负数以免和原始数据的正数id产生重复
              maintenanceGoingOn.begin_time = maintenance.begin_time
              maintenanceGoingOn.check_in_time = checkInTime
              maintenanceGoingOn.work = maintenance.work                              #当前进度条的工作和原进度条的工作相等
              maintenanceGoingOn.team = maintenance.team                              #当前进度条的团队和原进度条的团队相等
              maintenanceGoingOn.worker = maintenance.worker
              maintenanceGoingOn.description = getRecords maintenance.checkrecords
              maintenanceGoingOn.flag = -2                                            #新产生的进图条也会重新进入循环，因此要在此设置flag，以免循环产生新的进度条
              maintenanceGoingOn.title = maintenance.team.name.to_s + '的'+
                maintenance.work.name.to_s + "任务"
              maintenances.push(maintenanceGoingOn)                                   #将新建立出来的进图条插入到计划列表
              maintenancesTimer = maintenancesTimer - 1                               #计数器减一
            end

          else
            maintenanceFinish = Maintenance.new                                     #新建进度条
            #打卡开始时间减去总任务开始时间
            maintenanceFinish.check_in_time = checkInTime
            maintenanceFinish.check_out_time = checkOutTime
            maintenanceFinish.train_task_id = maintenance.train_task_id
            maintenanceFinish.id = maintenancesTimer                                #设置id，使用递减负数以免和原始数据的正数id产生重复
            maintenanceFinish.begin_time = maintenance.begin_time
            maintenanceFinish.work = maintenance.work                               #当前进度条的工作和原进度条的工作相等
            maintenanceFinish.team = maintenance.team                               #当前进度条的团队和原进度条的团队相等
            maintenanceFinish.worker = maintenance.worker
            maintenanceFinish.description = getRecords maintenance.checkrecords

            #静态作业正常结束，还没有供电
            if maintenance.flag.to_s == '3'
              maintenanceFinish.begin_minute =
                (DateTime.parse(checkInTime) - DateTime.parse(taskBeginTime))*24*60
              #              maintenanceFinish.finish_minute =
              #                (DateTime.parse(checkOutTime) - DateTime.parse(checkInTime))*24*60    #现在时间减去打卡开始时间

              if trainTask.power_time && trainTask.power_time < maintenance.check_out_time
                if trainTask.power_time > maintenance.check_in_time
                  maintenanceFinish.finish_minute =
                    (DateTime.parse(trainTask.power_time.to_s) - DateTime.parse(checkInTime))*24*60
                  maintenanceFinish.dynamic_finish_minute =
                    (DateTime.parse(checkOutTime) - DateTime.parse(trainTask.power_time.to_s))*24*60
                else
                  maintenanceFinish.dynamic_finish_minute =
                    (DateTime.parse(checkOutTime) - DateTime.parse(checkInTime))*24*60
                end
              else
                maintenanceFinish.finish_minute =
                  (DateTime.parse(checkOutTime) - DateTime.parse(checkInTime))*24*60
              end
              maintenanceFinish.flag = -3                                             #新产生的进图条也会重新进入循环，因此要在此设置flag，以免循环产生新的进度条
              maintenanceFinish.title = maintenanceFinish.team.name.to_s + '的'+
                maintenanceFinish.work.name.to_s + "任务"
            end

            #静态作业正常结束，已加电，开始动态任务
            if maintenance.flag.to_s == '4'
              maintenanceFinish.begin_minute =
                (DateTime.parse(checkInTime) - DateTime.parse(taskBeginTime))*24*60
              #              maintenanceFinish.finish_minute =
              #                (DateTime.parse(checkOutTime) - DateTime.parse(checkInTime))*24*60    #现在时间减去打卡开始时间

              if trainTask.power_time && (!maintenance.check_out_time || trainTask.power_time < maintenance.check_out_time)
                if trainTask.power_time > maintenance.check_in_time
                  maintenanceFinish.finish_minute =
                    (DateTime.parse(trainTask.power_time.to_s) - DateTime.parse(checkInTime))*24*60
                  maintenanceFinish.dynamic_finish_minute =
                    (DateTime.parse(checkOutTime) - DateTime.parse(trainTask.power_time.to_s))*24*60
                else
                  maintenanceFinish.dynamic_finish_minute =
                    (DateTime.parse(checkOutTime) - DateTime.parse(checkInTime))*24*60
                end
              else
                maintenanceFinish.finish_minute =
                  (DateTime.parse(checkOutTime) - DateTime.parse(checkInTime))*24*60
              end
              maintenanceFinish.flag = -4                                             #新产生的进图条也会重新进入循环，因此要在此设置flag，以免循环产生新的进度条
              maintenanceFinish.title = maintenanceFinish.team.name.to_s + '的'+
                maintenanceFinish.work.name.to_s + "任务"
              #如果已经有动态打开开始，加入动态打卡信息。
              if dynamicCheckInTime != '' && dynamicFlag == 1
                maintenanceFinish.dynamic_check_in_time = dynamicCheckInTime
                maintenanceFinish.foot_minute =
                  (DateTime.parse(dynamicCheckInTime) - DateTime.parse(checkOutTime))*24*60
                maintenanceFinish.dynamic_during_minute =
                  (DateTime.parse(nowTime) - DateTime.parse(dynamicCheckInTime))*24*60
              end
            end

            #静态作业调度结束，已加电，开始动态作业
            if maintenance.flag.to_s == '5'
              if checkInTime != ''
                maintenanceFinish.begin_minute =
                  (DateTime.parse(checkInTime) - DateTime.parse(taskBeginTime))*24*60
                #                maintenanceFinish.finish_minute =
                #                  (DateTime.parse(checkOutTime) - DateTime.parse(checkInTime))*24*60     #现在时间减去打卡开始时间
                if trainTask.power_time && (!maintenance.check_out_time || trainTask.power_time < maintenance.check_out_time)
                  if trainTask.power_time > maintenance.check_in_time
                    maintenanceFinish.finish_minute =
                      (DateTime.parse(trainTask.power_time.to_s) - DateTime.parse(checkInTime))*24*60
                    maintenanceFinish.dynamic_finish_minute =
                      (DateTime.parse(checkOutTime) - DateTime.parse(trainTask.power_time.to_s))*24*60
                  else
                    maintenanceFinish.finish_minute =
                      (DateTime.parse(checkOutTime) - DateTime.parse(checkInTime))*24*60
                  end
                else
                  maintenanceFinish.finish_minute =
                    (DateTime.parse(checkOutTime) - DateTime.parse(checkInTime))*24*60
                end
              end
              maintenanceFinish.flag = -5                                             #新产生的进图条也会重新进入循环，因此要在此设置flag，以免循环产生新的进度条
              maintenanceFinish.title = maintenanceFinish.team.name.to_s + '的'+
                maintenanceFinish.work.name.to_s + "任务"
              #如果已经有动态打开开始，加入动态打卡信息。
              if dynamicFlag == 1
                if dynamicCheckInTime != ''
                  if checkInTime != ''
                    maintenanceFinish.dynamic_check_in_time = dynamicCheckInTime
                    maintenanceFinish.foot_minute = (DateTime.parse(dynamicCheckInTime) - DateTime.parse(checkOutTime))*24*60
                    maintenanceFinish.dynamic_during_minute =
                      (DateTime.parse(nowTime) - DateTime.parse(dynamicCheckInTime))*24*60
                  else
                    maintenanceFinish.dynamic_check_in_time = dynamicCheckInTime
                    maintenanceFinish.foot_minute = (DateTime.parse(dynamicCheckInTime) - DateTime.parse(taskBeginTime))*24*60
                    maintenanceFinish.dynamic_during_minute =
                      (DateTime.parse(nowTime) - DateTime.parse(dynamicCheckInTime))*24*60
                  end
                end
                
              end
            end

            #静态作业正常结束，动态作业正常结束。
            if maintenance.flag.to_s == '6'
              maintenanceFinish.begin_minute =
                (DateTime.parse(checkInTime) - DateTime.parse(taskBeginTime))*24*60
              #              maintenanceFinish.finish_minute =
              #                (DateTime.parse(checkOutTime) - DateTime.parse(checkInTime))*24*60     #现在时间减去打卡开始时间#现在时间减去打卡开始时间
              if trainTask.power_time && trainTask.power_time < maintenance.check_out_time
                maintenanceFinish.finish_minute =
                  (DateTime.parse(trainTask.power_time.to_s) - DateTime.parse(checkInTime))*24*60
                maintenanceFinish.dynamic_finish_minute =
                  (DateTime.parse(checkOutTime) - DateTime.parse(trainTask.power_time.to_s))*24*60
              else
                maintenanceFinish.finish_minute =
                  (DateTime.parse(checkOutTime) - DateTime.parse(checkInTime))*24*60
              end
              
              maintenanceFinish.flag = -6                                             #新产生的进图条也会重新进入循环，因此要在此设置flag，以免循环产生新的进度条
              if dynamicFlag == 1
                maintenanceFinish.dynamic_check_in_time = dynamicCheckInTime
                maintenanceFinish.dynamic_check_out_time = dynamicCheckOutTime
                if dynamicCheckInTime != ''
                  maintenanceFinish.foot_minute = (DateTime.parse(dynamicCheckInTime) - DateTime.parse(checkOutTime))*24*60
                  maintenanceFinish.dynamic_finish_minute =
                    (DateTime.parse(dynamicCheckOutTime) - DateTime.parse(dynamicCheckInTime))*24*60
                end
                
              end
              maintenanceFinish.title = maintenanceFinish.team.name.to_s + '的'+
                maintenanceFinish.work.name.to_s + "任务"
            end

            #静态作业正常结束，动态作业调度结束
            if maintenance.flag.to_s == '7'
              maintenanceFinish.begin_minute =
                (DateTime.parse(checkInTime) - DateTime.parse(taskBeginTime))*24*60
              #              maintenanceFinish.finish_minute =
              #                (DateTime.parse(checkOutTime) - DateTime.parse(checkInTime))*24*60     #现在时间减去打卡开始时间
              if trainTask.power_time && trainTask.power_time < maintenance.check_out_time
                if trainTask.power_time > maintenance.check_in_time
                  maintenanceFinish.finish_minute =
                    (DateTime.parse(trainTask.power_time.to_s) - DateTime.parse(checkInTime))*24*60
                  maintenanceFinish.dynamic_finish_minute =
                    (DateTime.parse(checkOutTime) - DateTime.parse(trainTask.power_time.to_s))*24*60
                else
                  maintenanceFinish.dynamic_finish_minute =
                    (DateTime.parse(checkOutTime) - DateTime.parse(checkInTime))*24*60
                end
              else
                maintenanceFinish.finish_minute =
                  (DateTime.parse(checkOutTime) - DateTime.parse(checkInTime))*24*60
              end
              maintenanceFinish.flag = -7                                             #新产生的进图条也会重新进入循环，因此要在此设置flag，以免循环产生新的进度条
              if dynamicCheckInTime != '' && dynamicFlag == 1
                maintenanceFinish.dynamic_check_in_time = dynamicCheckInTime
                maintenanceFinish.dynamic_check_out_time = dynamicCheckOutTime
                maintenanceFinish.foot_minute = (DateTime.parse(dynamicCheckInTime) - DateTime.parse(checkOutTime))*24*60
                maintenanceFinish.dynamic_finish_minute =
                  (DateTime.parse(dynamicCheckOutTime) - DateTime.parse(dynamicCheckInTime))*24*60
              end
              maintenanceFinish.title = maintenanceFinish.team.name.to_s + '的'+
                maintenanceFinish.work.name.to_s + "任务"
            end

            #静态作业调度结束，动态作业正常结束
            if maintenance.flag.to_s == '8'
              if checkInTime != ''
                maintenanceFinish.begin_minute =
                  (DateTime.parse(checkInTime) - DateTime.parse(taskBeginTime))*24*60
                #                maintenanceFinish.finish_minute =
                #                  (DateTime.parse(checkOutTime) - DateTime.parse(checkInTime))*24*60
                if trainTask.power_time && trainTask.power_time < maintenance.check_out_time
                  maintenanceFinish.finish_minute =
                    (DateTime.parse(trainTask.power_time.to_s) - DateTime.parse(checkInTime))*24*60
                  maintenanceFinish.dynamic_finish_minute =
                    (DateTime.parse(checkOutTime) - DateTime.parse(trainTask.power_time.to_s))*24*60
                else
                  maintenanceFinish.finish_minute =
                    (DateTime.parse(checkOutTime) - DateTime.parse(checkInTime))*24*60
                end
              end
              
              maintenanceFinish.flag = -8                                             #新产生的进图条也会重新进入循环，因此要在此设置flag，以免循环产生新的进度条
              if dynamicFlag == 1
                maintenanceFinish.dynamic_check_in_time = dynamicCheckInTime
                maintenanceFinish.dynamic_check_out_time = dynamicCheckOutTime
                if checkInTime != ''
                  maintenanceFinish.foot_minute = (DateTime.parse(dynamicCheckInTime) -
                      DateTime.parse(checkOutTime))*24*60
                else
                  maintenanceFinish.foot_minute = (DateTime.parse(dynamicCheckInTime) - DateTime.parse(taskBeginTime))*24*60
                end
                
                maintenanceFinish.dynamic_finish_minute =
                  (DateTime.parse(dynamicCheckOutTime) - DateTime.parse(dynamicCheckInTime))*24*60
              end
              maintenanceFinish.title = maintenanceFinish.team.name.to_s + '的'+
                maintenanceFinish.work.name.to_s + "任务"
            end

            #静态作业调度结束，动态作业调度结束
            if maintenance.flag.to_s == '9'
              if checkInTime != ''
                maintenanceFinish.begin_minute =
                  (DateTime.parse(checkInTime) - DateTime.parse(taskBeginTime))*24*60
                #                maintenanceFinish.finish_minute =
                #                  (DateTime.parse(checkOutTime) - DateTime.parse(checkInTime))*24*60
                if trainTask.power_time && trainTask.power_time < maintenance.check_out_time
                  if trainTask.power_time > maintenance.check_in_time
                    maintenanceFinish.finish_minute =
                      (DateTime.parse(trainTask.power_time.to_s) - DateTime.parse(checkInTime))*24*60
                    maintenanceFinish.dynamic_finish_minute =
                      (DateTime.parse(checkOutTime) - DateTime.parse(trainTask.power_time.to_s))*24*60
                  else
                    maintenanceFinish.dynamic_finish_minute =
                      (DateTime.parse(checkOutTime) - DateTime.parse(checkInTime))*24*60
                  end
                  
                else
                  maintenanceFinish.finish_minute =
                    (DateTime.parse(checkOutTime) - DateTime.parse(checkInTime))*24*60
                end
              end
              maintenanceFinish.flag = -9                                             #新产生的进图条也会重新进入循环，因此要在此设置flag，以免循环产生新的进度条
              if dynamicFlag == 1
                maintenanceFinish.dynamic_check_in_time = dynamicCheckInTime
                maintenanceFinish.dynamic_check_out_time = dynamicCheckOutTime
                if dynamicCheckInTime != ''
                  if checkInTime != ''
                    maintenanceFinish.foot_minute = (DateTime.parse(dynamicCheckInTime) - DateTime.parse(checkOutTime))*24*60
                  else
                    maintenanceFinish.foot_minute = (DateTime.parse(dynamicCheckInTime) - DateTime.parse(taskBeginTime))*24*60
                  end
                  maintenanceFinish.dynamic_finish_minute =
                    (DateTime.parse(dynamicCheckOutTime) - DateTime.parse(dynamicCheckInTime))*24*60
                end
                
              end
              maintenanceFinish.title = maintenanceFinish.team.name.to_s + '的'+
                maintenanceFinish.work.name.to_s + "任务"
            end
            if checkInTime != '' || dynamicCheckInTime != ''
              maintenances.push(maintenanceFinish)                                    #将新建立出来的进图条插入到计划列表
            end
            
            maintenancesTimer = maintenancesTimer - 1                               #计数器减一
          end
        end
      end
    end
    shutDownMaintenance.id = 0                                                  #你想按照id排序，必须给这个没有Id的shutDownMaintenance赋上个值
    maintenances.push(shutDownMaintenance)
    maintenancesSorted = maintenances.sort_by{ |a| [a.begin_time,a.team_id,-a.id]}    #进行排序，先根据时间，再根据组队，再根据a的id得倒序（每一个对象都有begin_time，只是不用来显示）
    jsonstr='{total:' + maintenancesSorted.length.to_s + ',root:' +
      maintenancesSorted.to_json(:include => [:work,:team,:worker]) + '}'               #组合json串
    render :text=>jsonstr, :layout=>false
    
  end


  def getWorker checkrecords
    string = ''
    checkrecords.each do |cc|
      string << cc.worker.name.to_s+' '
    end
    if string == ''
      return '暂无'
    else
      return string
    end
  end

  def getRecords checkrecords
    string = ''
    checkrecords.each do |cc|
      string << '打卡人：'+cc.worker.name.to_s+'<br />'
      if cc.check_in_time
        string << '静态开始时间：'+cc.check_in_time.strftime("%Y-%m-%d %H:%M:%S")+'<br />'
        string << '静态结束时间：'+(cc.check_out_time.strftime("%Y-%m-%d %H:%M:%S") if cc.check_out_time).to_s+'<br />'
      end
      if cc.dynamic_check_in_time
        string << '动态开始时间：'+cc.dynamic_check_in_time.strftime("%Y-%m-%d %H:%M:%S")+'<br />'
        string << '动态结束时间：'+(cc.dynamic_check_out_time.strftime("%Y-%m-%d %H:%M:%S") if cc.dynamic_check_out_time).to_s+'<br />'
      end
      string << '--------------------------------------------------------------------<br />'
    end
    if string == ''
      return '暂无'
    else
      return string
    end
  end

  #接收打卡人员信息（组队中，只有设定的组长才能打卡）
  def addCheck
    begin
      worker = Worker.find(:first,
        :conditions => ["number = ?",params[:anSEnrollNumber].to_s])              #找到打卡的人

      track = Track.find(:first,:conditions => ['device_id = ?',params[:vnDeviceID].to_i])
      #打卡的人在系统中是否存在
      if worker
        #通过设备ID和员工组队找到maintenance
        maintenance = Maintenance.findByTeamAndTrainTask worker.team_id,params[:vnDeviceID].to_s
        
        if maintenance
          #0-上班  2-加班 1-下班  3-结束
          if params[:anInOutMode].to_s  == "0" || params[:anInOutMode].to_s == "2"   #打卡上班
            addCheckIn(maintenance,worker.id)
          elsif params[:anInOutMode].to_s == "1" || params[:anInOutMode].to_s == "3" #打卡下班
            addCheckOut(maintenance,worker.id)
          end
          #判断是否是长车作业，长车作业是指一列车太长，需要在两个相连的股道上作业。
          smaintenance = Maintenance.findByTeamAndTrainTask worker.team_id,track.sametrack.device_id.to_s
          #判断和开卡股道在同一轨道上的股道上，是否正在有检修作业，并判断两个股道的检修作业是否是同一列车
          if smaintenance && smaintenance.train.id == maintenance.train.id
            if params[:anInOutMode].to_s  == "0" || params[:anInOutMode].to_s == "2"   #打卡上班
              addCheckIn(smaintenance,worker.id)
            elsif params[:anInOutMode].to_s == "1" || params[:anInOutMode].to_s == "3" #打卡下班
              addCheckOut(smaintenance,worker.id)
            end
          end
        end
        
        
        #添加打卡记录
        addRecord worker,params[:anInOutMode].to_s,track
      end
    rescue Exception => e
      logger.info e
      DbLog.info(params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
    
    render :text => 'success',:layout => false
    
  end

  private

  #增加人员打指纹记录
  def addRecord worker,mode,track
    train_task = TrainTask.where("device_id = "+track.device_id.to_s).order("created_at DESC").first
    if train_task.is_end == 1
      train_name = '暂无'
    else
      train_name = (train_task.train ? train_task.train.sn : '暂无')
    end
    Record.create(:worker => worker,:check_time => Time.now,:check_type => mode.to_i,
      :track => track,:train_name => train_name,
      :team_name => worker.team ? worker.team.name : '')
  end

  #设置打卡开工时间，并开始工作
  def addCheckIn maintenance,worker_id
    begin
      dflag = maintenance.train_task.is_end
      crecord = Checkrecord.find(:first,:conditions => ['maintenance_id = ? AND worker_id = ?',maintenance.id,worker_id])
      #静态作业
      if dflag == 2
        #判断该员工针对这个maintenance是否打过指纹，如果没打过，则创建checkrecord
        unless crecord
          checkrecord = Checkrecord.new
          checkrecord.check_in_time = Time.now
          checkrecord.maintenance_id = maintenance.id
          checkrecord.worker_id = worker_id
          checkrecord.train_task_id = maintenance.train_task_id
          checkrecord.flag = 0
          #检查员工是否是控制人员
          if check_manager worker_id
            #maintenance是否已开始，没有开始，则把当前时间记录为任务开始时间
            if maintenance.check_in_time == nil
              maintenance.check_in_time = Time.now
            end
            maintenance.flag = '2'
            maintenance.checkrecords << checkrecord
            maintenance.save!
          else
            checkrecord.save!
          end
        end
      end


      #动态作业
      if dflag == 3
        if maintenance.dynamic_flag == 1
          if crecord
            unless crecord.dynamic_check_in_time
              crecord.dynamic_check_in_time = Time.now
              if check_manager worker_id
                unless maintenance.dynamic_check_in_time
                  maintenance.dynamic_check_in_time = Time.now
                  maintenance.save!
                end
              end
              crecord.save!
            end
          else
            checkrecord = Checkrecord.new
            checkrecord.dynamic_check_in_time = Time.now
            checkrecord.maintenance_id = maintenance.id
            checkrecord.worker_id = worker_id
            checkrecord.train_task_id = maintenance.train_task_id
            checkrecord.dynamic_flag = 0
            if check_manager(worker_id)
              if maintenance.dynamic_check_in_time == nil
                maintenance.dynamic_check_in_time = Time.now
              end
              if maintenance.flag == '6'
                maintenance.flag = '4'
              elsif maintenance.flag == '8'
                maintenance.flag = '5'
              end
              maintenance.checkrecords << checkrecord
              maintenance.save!
            else
              checkrecord.save!
            end
          end
        else
          unless crecord
            checkrecord = Checkrecord.new
            checkrecord.check_in_time = Time.now
            checkrecord.maintenance_id = maintenance.id
            checkrecord.worker_id = worker_id
            checkrecord.train_task_id = maintenance.train_task_id
            checkrecord.flag = 0
            #打开员工是否是控制人员，maintenance是否已标记开始
            if check_manager(worker_id)
              if maintenance.check_in_time == nil
                maintenance.check_in_time = Time.now
              end
              maintenance.flag = '2'
              maintenance.checkrecords << checkrecord
              maintenance.save!
            else
              checkrecord.save!
            end
          end
        end
      end
    rescue Exception=>e
      logger.info e.to_s
    end
  end
  
  #设置打卡完工时间，并结束工作
  def addCheckOut maintenance,worker_id
    begin
      dflag = maintenance.train_task.is_end
      checkrecords = maintenance.checkrecords
      
      #静态作业,maintenance.flag只能为1,2,3
      if dflag == 2
        unless check_maintenance(maintenance)
          flag = checkrecords.index {|x| x.worker_id == worker_id}  #判断checkrecords中是否有worker_id的信息
          if flag
            crecord = checkrecords.fetch(flag)          #有worker_id的话，获取该worker_id所属的checkrecord
            crecord.check_out_time = Time.now
            crecord.flag = 1
            crecord.save!
            if check_maintenance(crecord.maintenance)
              maintenance.check_out_time = Time.now
              maintenance.flag = '3'
              maintenance.save!
            end
          end
        end
      end
      
      #动态作业
      if dflag == 3
        if maintenance.dynamic_flag == 1
          unless check_dynamic_maintenance(maintenance)
            flag = checkrecords.index {|x| x.worker_id == worker_id}  #判断checkrecords中是否有worker_id的信息
            if flag
              crecord = checkrecords.fetch(flag)          #有worker_id的话，获取该worker_id所属的checkrecord
              crecord.dynamic_check_out_time = Time.now
              crecord.dynamic_flag = 1
              crecord.save!
              if check_dynamic_maintenance(crecord.maintenance)
                maintenance.dynamic_check_out_time = Time.now
                if maintenance.flag == '4'
                  maintenance.flag = '6'
                elsif maintenance.flag == '5'
                  maintenance.flag = '8'
                end
                maintenance.save!
              end
            end
          end
        else
          unless check_maintenance(maintenance)
            flag = checkrecords.index {|x| x.worker_id == worker_id}  #判断checkrecords中是否有worker_id的信息
            if flag
              crecord = checkrecords.fetch(flag)          #有worker_id的话，获取该worker_id所属的checkrecord
              crecord.check_out_time = Time.now
              crecord.flag = 1
              crecord.save!
              if check_maintenance(crecord.maintenance)
                if maintenance.dynamic_flag != 2
                  maintenance.check_out_time = Time.now
                  maintenance.flag = '3'
                  maintenance.save!
                end
              end
            end
          end
        end
        
      end
      
    rescue Exception=>e
      logger.info e.to_s
    end
  end

  #检查worker是否是manager
  def check_manager worker_id
    worker = Worker.find_by_id worker_id
    flag = worker ? worker.is_manager : nil
    if flag && flag == '1'
      return true
    else
      return false
    end
  end

  #检查maintenance所有的checkrecords是否都已经结束。
  def check_maintenance maintenance
    maintenance.checkrecords.each do |record|
      #控制人员中只要有一人未完成，就返回false
      return false if (record.worker ? record.worker.is_manager : nil) == '1' && record.flag == '0'
    end
    return true
  end

  #检查maintenance所有的checkrecords是否都已经结束。(动态)
  def check_dynamic_maintenance maintenance
    maintenance.checkrecords.each do |record|
      #控制人员中只要有一人未完成，就返回false
      if (record.worker ? record.worker.is_manager : nil) == '1' && record.dynamic_flag == 0
        return false
      end
    end
    return true
  end

end
